package com.deyuanyun.pic.settings.support.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.deyuanyun.pic.common.util.StringUtils;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;

/**
 * @author xiatao
 *         时间:2015年08月19日 14时07分18秒
 *         excel导出导入工具类
 * CK：2016-06-27，建议使用com.deyuanyun.pic.common.util.poi.ExcelUtil.initWorkbook(filePath, listSheets, beginRows)来导出。
 */
@Deprecated
public class ExcelUtils {

    //日志记录
    private static Logger log = LogManager.getLogger(ExcelUtils.class);

    /**
     * jxl导出excel工具类
     *
     * @param filePath  模板文件路径
     * @param lineStart 从第几行开始写入数组
     * @param excelName excel文件名
     * @param list      导出的内容list
     * @param response  response响应
     */
    public static void jxlExportExcel(String filePath, int[] lineStart, String excelName, List<List<String[]>> list, HttpServletResponse response) {
        Workbook wb = null;
        try {
            //1.选择excel的模板文件
            wb = Workbook.getWorkbook(new File(filePath));
        } catch (IOException e) {
            log.error(e);
        } catch (BiffException e) {
            log.error(e);
        }
        exportExcel(wb, lineStart, excelName, list, response);
    }

    private static void exportExcel(Workbook wb, int[] lineStart, String excelName, List<List<String[]>> list, HttpServletResponse response) {
        WritableWorkbook workbook = null;
        BufferedOutputStream bufferedOutputStream = null;
        ServletOutputStream outputStream = null;
        try {

            outputStream = response.getOutputStream();
            //2.创建一个字节输出流
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            //3.通过模板得到一个可写的Workbook
            workbook = Workbook.createWorkbook(bufferedOutputStream, wb);
            WritableCellFormat style = new WritableCellFormat(NumberFormats.TEXT);
            //5.1水平居中
            style.setAlignment(jxl.format.Alignment.CENTRE);

            //K代表集合包含对象个数
            for (int k = 0; k < list.size(); k++) {

                if (null != list.get(k) && 0 != list.get(k).size()) {
                    System.err.println("***************");
                    //4.创建sheet
                    WritableSheet sheet = workbook.getSheet(k);
                    //5样式设置
                    //6.sheet添加单元格内容
                    	    
                    /* System.err.println("当前有:"+list.get(k).size()+"行");*/
                    //循环行数
                    for (int i = 0; i < list.get(k).size(); i++) {
                        //循环列数
                        for (int j = 0; j < list.get(k).get(i).length; j++) {

                            //6.1四个参数(单元格列，单元格行，内容，样式)
                            String cellValue = list.get(k).get(i)[j];
                            Label lab = new Label(j, i + lineStart[k], cellValue, style);
                            sheet.addCell(lab);
                            /* System.err.println("第"+k+"页选项卡第"+i+"行第"+j+"列的值为"+cellValue);*/
//                            sheet.addCell(new Label(j, i + lineStart[k], cellValue, style));
                        }
                    }
                }
            }
            workbook.write();
            excelName = excelName + ".xls";
            response.setHeader("Content-disposition", "attachment; filename=" + new String(excelName.getBytes(), "iso-8859-1"));
            response.setContentType("application/msexcel");
        } catch (FileNotFoundException e) {
            log.error("excel导出模板文件没有找到，详情如下：\n" + e);
        } catch (IOException e) {
            log.error("excel导出模板文件读取IO异常，详情如下：\n" + e);
        } catch (Exception e) {
            //异常日志记录
            log.error(e);
            StackTraceElement[] stackTrace = e.getStackTrace();
            for (StackTraceElement stackTraceElement : stackTrace) {
                log.error(stackTraceElement.toString());
            }
        } finally {
            try {
                workbook.close();
                outputStream.close();
            } catch (Exception e) {
                //异常日志记录
                log.error(e.getMessage());
                StackTraceElement[] stackTrace = e.getStackTrace();
                for (StackTraceElement stackTraceElement : stackTrace) {
                    log.error(stackTraceElement.toString());
                }
            }
            wb.close();
        }
    }

    /**
     * @param inputStream
     * @param lineStart
     * @param excelName
     * @param list
     * @param response
     */
    public static void jxlExportExcel(InputStream inputStream, int[] lineStart, String excelName, List<List<String[]>> list, HttpServletResponse response) {
        boolean isempty = true;
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (!ObjectUtil.isEmptyAll(list.get(i))) {
                    isempty = false;
                }
            }
        }
        if (isempty) {
            response.setHeader("Content-Disposition", "");
            AjaxResponse.sendText(response, "<script>alert('数据为空，不可进行下载操作!');window.close();</script>");
            return;
        }


        Workbook wb = null;
        try {
            //1.选择excel的模板文件
            wb = Workbook.getWorkbook(inputStream);
        } catch (IOException e) {
            log.error(e);
            return;
        } catch (BiffException e) {
            log.error(e);
            return;
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
        exportExcel(wb, lineStart, excelName, list, response);
    }


    public static void jxlExportExcel(InputStream inputStream, int[] lineStart, String excelName,
                                      List<List<String[]>> list, HttpServletResponse response,
                                      HttpServletRequest request) {
        StringBuffer name=new StringBuffer();
        String lineName=request.getParameter("lineName");
        String taskName=request.getParameter("taskName");
        String apprarse=request.getParameter("apprarse");
        if(null != lineName)
        {
            name.append(lineName);
        }
        if(null != taskName)
        {
            name.append(taskName);
        }
        name.append(excelName);
        if(null != apprarse)
        {
            name.append(apprarse);
        }
        name.append(StringUtils.convertDateToString(new Date(),"yyyyMMdd"));
        jxlExportExcel(inputStream, lineStart, name.toString(), list, response);
    }
}